import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class WindowMenu extends JFrame implements ActionListener {


    private final String[] newEcM = {"订单编号", "收件人", "固话", "手机", "地址", "发货信息", "宝贝数量", "总重量", "备注",
            "代收金额", "保价金额", "业务类型", "实付金额"};

    private final String[] oldEcM = {"订单号", "收货人", "手机", "手机", "省#&市#&区#&街道", "商品规格", "商品数量(件)", "总重量", "商家备注",
            "代收金额", "保价金额", "业务类型", "实付金额"};

    private List<List<String>> lists = new ArrayList<>();

    private final String XLSX = "xlsx";
    private final String XLS = "xls";
    private final String CSV = "csv";

    private String inName = "";

    JButton button;

    public WindowMenu(String s, int x, int y, int w, int h) {
        init(s);
        this.setLocation(x, y);
        this.setSize(w, h);
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    void init(String s) {
        setTitle(s);
        JMenu menu1 = new JMenu("文件");
        addItem(menu1, "导入原文件", this);
        addItem(menu1, "导出新文件至桌面", this);
        addItem(menu1, "退出", this);
        JMenuBar menubar = new JMenuBar();
        menubar.add(menu1);
        setJMenuBar(menubar);
        button = new JButton("格式化表格文件");
        button.setActionCommand("格式化表格文件");
        button.addActionListener(this);
        add(button);
    }

    private void addItem(JMenu Menu, String menuName, ActionListener listener) {
        JMenuItem anItem = new JMenuItem(menuName);
        anItem.setActionCommand(menuName);
        anItem.addActionListener(listener);
        Menu.add(anItem);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand() + "");
        switch (e.getActionCommand()) {
            case "导入原文件":
                openFileChooser();
                break;
            case "导出新文件至桌面":
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
//                ExcelTool.saveHSSFWorkbook(inName + "_" + simpleDateFormat.format(new Date()) + ".xls", "sheet", newEcM, lists);
                do_menuItem_actionPerformed();
                break;
            case "退出":
                System.exit(0);
                break;
            case "格式化表格文件":
                openFileChooser();
//                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
//                ExcelTool.saveHSSFWorkbook(inName + "_" + simpleDateFormat1.format(new Date()) + ".xls", "sheet", newEcM, lists);
                do_menuItem_actionPerformed();
                break;
            default:
                break;
        }
    }

    private void openFileChooser() {
        JFileChooser chooser = new JFileChooser();
        FileSystemView fsv = FileSystemView.getFileSystemView();
        //过滤可以选择的文件
        System.out.println(fsv.getHomeDirectory());
        chooser.setCurrentDirectory(fsv.getHomeDirectory());
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Allowed File", CSV);
        chooser.setFileFilter(filter);
        chooser.setMultiSelectionEnabled(false);
        chooser.showDialog(new JLabel(), "选择");
        File file = chooser.getSelectedFile();
        if (file != null) {
            System.out.println(file.getAbsoluteFile().toString() + "被選中");
            inName = file.getName().substring(0, file.getName().lastIndexOf("."));
            readExcel(file);
        }
    }

    public void readExcel(File file) {
        InputStream is;
        try {
            is = new FileInputStream(file);
            if (file.getAbsolutePath().endsWith(CSV)) {
                lists = ExcelTool.read(is, oldEcM);
            } else {
                JOptionPane.showMessageDialog(null, "文件格式错误，请重试.", "error", JOptionPane.ERROR_MESSAGE);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "系统发生错误，请重试.", "error", JOptionPane.ERROR_MESSAGE);
        }
    }

    protected void do_menuItem_actionPerformed() {
        if (lists == null || lists.isEmpty()) {
            return;
        }
        JFileChooser chooser = new JFileChooser();
        FileSystemView fsv = FileSystemView.getFileSystemView();
        //过滤可以选择的文件
        System.out.println(fsv.getHomeDirectory());
        chooser.setCurrentDirectory(fsv.getHomeDirectory());
        FileNameExtensionFilter filter = new FileNameExtensionFilter(XLS, XLS);
        chooser.setFileFilter(filter);
        int option = chooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            String fname = chooser.getName(file);    //从文件名输入框中获取文件名
            if (!fname.contains(XLS)) {
                file = new File(chooser.getCurrentDirectory(), fname + "." + XLS);
            }
            ExcelTool.saveHSSFWorkbook(file, "sheet", newEcM, lists);
        }
    }
}